import { cloneDeep  } from 'lodash'
export const getUrlLastStr = (pathStr) => {
  if (!String(pathStr)) return ''
  if (pathStr.indexOf('?') > 0) {
    pathStr = pathStr.split('?')[0];
  } 
  const parts = pathStr.split('/')
  const param = parts.pop() || parts.pop()
  return param
}
export const getUrlNumStr = (pathStr, num) => {
  if (!String(pathStr)) return ''
  if(pathStr.indexOf("?") >= 0) {
    pathStr = pathStr.split("?")[0]
  }
  const parts = pathStr.split('/')
  return parts[(parts.length- 1 - num)]
}
// 图片地址
export const imgBase = "/static/img";
export const logoUrl = "//img-md.veimg.cn/meadinindex/";

// 初始参数
export const initData = {
  hrefPc: '//i.meadin.com/',
  NODE_URL: process.env.NODE_URL,
  hrefM: process.env.NODE_URL === 'test' ? '//10.10.29.205:8090/' : '//index.meadin.com/',
  title: '迈点指数_index.meadin.com - 商业空间产业品牌价值查询平台',
  keywords: '品牌指数,点评指数,MBI,MCI,搜索指数,运营指数,点评指数,媒体指数',
  description: '迈点指数是根据迈点研究院独家发布的指数获得的酒店、景区、文旅、公寓、办公、商业、物业等商业空间产业品牌及单店数据排行榜,从搜索、媒体、点评、运营等维度综合评价品牌及单店运营情况。',
  author: 'dfws',
  mbiDefaultImg: `${imgBase}/mbi.jpg`,
  mciDefaultImg: `${imgBase}/mci.jpg`,
  mviDefaultImg: `${imgBase}/mvi.png`,
  mbiStartDate: {
    1101: '2011-7',
    1103: '2011-7',
    1104: '2011-7',
    1105: '2018-7',
  },
  topMenu:[
    {
      name: '旅游住宿',
      type: 1,
      indexType: 1101,
      icon: 'tourist.png',
      typeId: 15,
      startData: '2011-7',
    },
    {
      name: '旅游住宿1',
      type: 1,
      indexType: 1101,
      icon: 'tourist.png',
      typeId: 15,
      startData: '2011-7',
    },
    {
      name: '住房租赁',
      type: 2,
      typeId: 43,
      icon: 'rent.png',
      indexType: 1103,
      startData: '2011-7',
    },
    {
      name: '文旅景区',
      type: 4,
      typeId: 56,
      icon: 'scenic.png',
      indexType: 1105,
      startData: '2018-7',
    },
    {
      name: '其他',
      type: 3,
      typeId: 37,
      icon: 'facilitator.png',
      indexType: 1104,
      startData: '2011-7',
    },
  ],
  meadiaUpDate: {
    rows: []
  },
  openId: '',
  mbiTypeActive: 1,
  mbiTypeNum: 1101,
  mciTypeNum: 1102,
  mciStartDate: '2015-1',
  mviStartDate: '2020-12',
  tourismStartDate: '2021-07-01',
  createStrategy: 2, // 生成周期 月
  brandId: 15,
  typeId: 15,
  cityId: 1,
  currentPage: 1,
  showCount: 10,
  timeList: [
    {
      name: '近7天',
      id: 1,
    },
    {
      name: '近15天',
      id: 2,
    },
    {
      name: '近30天',
      id: 3,
    }
  ],
  meadiaList: [
    {
      name: '近7天',
      id: 1,
    },
    {
      name: '近30天',
      id: 2,
    },
    {
      name: '近60天',
      id: 3,
    },
    {
      name: '近90天',
      id: 4,
    }
  ],
  active: 1,
  reviewList: [
    {
      name: '推荐',
      id: 4,
    },
    {
      name: '好评',
      id: 1,
    },
    {
      name: '中评',
      id: 2,
    },
    {
      name: '差评',
      id: 3,
    },
  ],
  pkCommentData: [],
  provinceList: [{
    code: 110000,
    name: "北京",
  }, {
    code: 310000,
    name: "上海",
  }, {
    code: 120000,
    name: "天津",
  }, {
    code: 500000,
    name: "重庆",
  }, {
    code: 230000,
    name: "黑龙江",
  }, {
    code: 210000,
    name: "辽宁",
  }, {
    code: 220000,
    name: "吉林",
  }, {
    code: 130000,
    name: "河北",
  }, {
    code: 410000,
    name: "河南",
  }, {
    code: 420000,
    name: "湖北",
  }, {
    code: 430000,
    name: "湖南",
  }, {
    code: 370000,
    name: "山东",
  }, {
    code: 140000,
    name: "山西",
  }, {
    code: 340000,
    name: "安徽",
  }, {
    code: 330000,
    name: "浙江",
  }, {
    code: 320000,
    name: "江苏",
  }, {
    code: 350000,
    name: "福建",
  }, {
    code: 440000,
    name: "广东",
  }, {
    code: 460000,
    name: "海南",
  }, {
    code: 510000,
    name: "四川",
  }, {
    code: 530000,
    name: "云南",
  }, {
    code: 520000,
    name: "贵州",
  }, {
    code: 630000,
    name: "青海",
  }, {
    code: 620000,
    name: "甘肃",
  }, {
    code: 360000,
    name: "江西",
  },
  //  {
  //   code: 710000,
  //   name: "台湾",
  // }, 
  {
    code: 150000,
    name: "内蒙古",
  }, {
    code: 640000,
    name: "宁夏",
  }, {
    code: 650000,
    name: "新疆",
  }, {
    code: 540000,
    name: "西藏",
  }, {
    code: 450000,
    name: "广西",
  },
  //  {
  //   code: 810000,
  //   name: "香港",
  // }, {
  //   code: 820000,
  //   name: "澳门",
  // }, 
  {
    code: 610000,
    name: "陕西",
  }],
  cityCode: '',
  cityName: '全国',
  scenicTree: [],
  scenicId: '',
  platform: false,
  shareCustomDetail: {},
  associationName: '',
  mbiNavFormat: []
}
export const urlSearch = function(url){
    var param = {};
    url = decodeURIComponent(url) 
    var num = url.indexOf("?")
    url = url.substr(num + 1);

    var arr = url.split("&");
    arr.map((v, i) => {
      num = v.indexOf("=");
      if (num > 0) {
          var name = v.substring(0, num);
          var value = v.substr(num + 1);
          param[name] = value;
      }
    })
    return param;
};

// 时间按钮遍历
export const timeBtn = ({year, month, startData}) => {
  if (month == 1) {
      return [
          {
              year: year - 1,
              month: 12-1
          },
          {
              year: year - 1,
              month: 12
          },
          {
              year: year,
              month: month
          }
      ]
  } else if (month == 2) {
      return [
          {
              year: year - 1,
              month: 12
          },
          {
              year: year,
              month: 1
          },
          {
              year: year,
              month: month
          }
      ]
  } else if (month >= 3) {
     var startYear = startData.split('-')[0], startMonth = startData.split('-')[1];
          if (startData && startYear == year) {
              if (month >= startMonth) {
                if (month == startMonth ) {
                  return [
                    {
                      year: year,
                      month: month
                    }
                  ]
                }else if (month - startMonth > 0) {
                  var b = month - startMonth;
                   var l = [];
                  for(var c = 0; b >= c; c++ ) {
                    l.push({
                      year: year,
                      month: month - c
                    })
                  }
                  return l.slice(0,3).reverse();
                }
              } 
          }
      var list = [];
      for (var a = 0; 3 > a; a++) {
          list.push(month-a)
      }
      list.reverse();
      var time = [];
      for (var i = 0; list.length > i; i++) {
          var ym = {
              year: year,
              month: list[i]
          }
          time.push(ym);
      }
      return time;
      
  }else{
      console.error("month 月份参数小于零");
      return false;
  }
}

// export const mbiTypeClassify = (arr) => {
//   let data = initData.topMenu;
//   for (let n of arr) {
//     for (let i of data) {
//       if (i.type == n.type) {
//        i.list = i.list.concat(n);
//       }
//     }
//   }
//   return list;
// }

// 前三 icon 
export const topThree = (ranking) => {
  switch (ranking) {
    case 1:
      return `<img src="${imgBase}/ranking-one.png" alt=${ranking} />`
    case 2:
      return `<img src="${imgBase}/ranking-two.png" alt=${ranking} />` 
    case 3:
      return `<img src="${imgBase}/ranking-three.png" alt=${ranking} />`
    default: 
      return ranking;
  }
}
// mci 获取大类型
export const mciTopMenu = (item) => {
  switch (item.id) {
    case 9:
      return '城市分类'
    case 10:
      return '功能分类'
    case 11:
      return '特色分类'
    default: 
      return item.name;
  }
}

export const riseRanking = (riseRanking) => {
  if (riseRanking > 0) {
    return `<img src="${imgBase}/up-rise.png" />`
  } else if (riseRanking < 0) {
    return `<img src="${imgBase}/dow-rise.png" />`
  } else {
    return `<img src="${imgBase}/rise-icon.png" />`
  }
} 
export const rankingType = (riseRanking) => {
  if (riseRanking > 0) {
    return {
      rankingNum: `↑ ${Math.abs(riseRanking)}`,
      styleC: 'up'
    }
  } else if (riseRanking < 0) {
    return {
      rankingNum: `↓ ${Math.abs(riseRanking)}`,
      styleC: 'down'
    }
  } else {
    return {
      rankingNum: `-`,
      styleC: 'plane'
    }
  }
} 

// 是否上升: 1下降 2持平 3上升 ,
export const isRanking = (riseRanking) => {
  if (riseRanking === 3) {
    return {
      img: `<img src="${imgBase}/up-rise.png" />`,
      colorClass: 'red-dd'
    }
  } else if (riseRanking === 1) {
    return {
      img: `<img src="${imgBase}/dow-rise.png" />`,
      colorClass: 'green-dd'
    }
  } else {
    return {
      img: `<img src="${imgBase}/rise-icon.png" />`,
      colorClass: ''
    }
  }
} 


// date yyyy-mm-dd
export const dateFormat = (date) => {
  if (date != null && date != undefined) {
    date =  date.substr(0, 10)
  } else {
    date = ''
  }
  // return `${date}${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
  return `${date}`
}


// mm
export const dateMonthFormat = (month) => {
  month = month + 1;
  if (month < 10) {
    return `0${month}`
  } else {
    return month
  }
}

export const evaluateLv = (num) => {
  if (num > 60) {
    return {text: '好评', icon: `${imgBase}/star-full.png`, color: 'level-good' }
  } else if (num <= 60 && num >= 40) {
    return {text: '中评', icon: `${imgBase}/star-three.png`, color: 'level-middle' }
  } else {
    return {text: '差评', icon: `${imgBase}/star-one.png`, color: 'level-bad'}
  }
}
// 随机数
export const rnd = (n, m) => {
    var random = Math.floor(Math.random()*(m-n+1)+n);
    return random;
}
// chart date format 
/* 
  dayType yyyy.mm， mm.dd， m月
*/ 
export const RankingChangeData = (data, name, needLen, dateType) => {
  let rdata = []
  data.map((item, index) => {
    for (const i of item) {
      i.name = name[index];
      if (dateType === 'mm') {
        i.date = `${dateMonthFormat(new Date(i.rankingDate * 1000).getMonth())}月` 
      } else {
        i.date = `${new Date(i.rankingDate * 1000).getFullYear()}.${dateMonthFormat(new Date(i.rankingDate * 1000).getMonth())}` 
      }
    }
    if (needLen != undefined) {
      rdata.push(...item.slice(item.length- needLen, item.length))
    } else {
      rdata.push(...item)
    }
  })
  return rdata;
}
// 字长截取
export const cutString = (data, len) => {
  if (data.length > len) {
    return `${data.slice(0, len)}...`;
  } else {
    return data
  }
}

export const nullChange = (data) => {
  if (data === undefined || data === null) {
    return 0;
  }
  return data;
}

export const isUndefined = (data, block) => {
  if (data != undefined && data != null) {
    return block;
  }
}

export const wxShareContent = (title, desc, img) => {
  const wx = window.wx;
  const res = {
    appid: "wx7ee666aa7eb3de32",
    timestamp: "1551165104",
    nonceStr: "403cba69-dcd2-4221-b687-6f7f28729848",
    signature: "c78da8616e9db4a5381fa3d30036a22efacdac98",
  }
  wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: res.appid, // 必填，公众号的唯一标识
    timestamp: res.timestamp, // 必填，生成签名的时间戳
    nonceStr: res.nonceStr, // 必填，生成签名的随机串
    signature: res.signature, // 必填，签名，见附录1
    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareWeibo'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
  });
  
}

// 设备判断 并跳转
export const browserRedirect: (url: string) => void = function(url) {
  var sUserAgent= window.navigator.userAgent.toLowerCase();
  var bIsIpad= sUserAgent.match(/ipad/i)[0] === "ipad";
  var bIsIphoneOs= sUserAgent.match(/iphone os/i)[0]  == "iphone os";
  var bIsMidp= sUserAgent.match(/midp/i)[0]  == "midp";
  var bIsUc7= sUserAgent.match(/rv:1.2.3.4/i)[0]  == "rv:1.2.3.4";
  var bIsUc= sUserAgent.match(/ucweb/i)[0]  == "ucweb";
  var bIsAndroid= sUserAgent.match(/android/i)[0]  == "android";
  var bIsCE= sUserAgent.match(/windows ce/i)[0]  == "windows ce";
  var bIsWM= sUserAgent.match(/windows mobile/i)[0]  == "windows mobile";
  const urls = url ? url : '';
  if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
  } else {
    window.location.href= `${initData.hrefPc + urls}`;
  }
}
//  获取品牌类型名称
export const getMbiTypeName = function(typeList, typeId) {
  let name;
  typeList.forEach(element => {
    Number(typeId) === element.typeId && (name = element.typeName)
  });
  return name
}

export const cutContent = function(data = '', leng, omit = true) {
  let d = data;
  if (leng > 0 && data.length > leng) {
    omit && (d = `${data.substr(0, leng)}...`);
    !omit && (d = `${data.substr(0, leng)}`);
  }
  return d;
}

export const formatYearM = function(parse) {
  var list = parse.split('-');
  return list[0] + "年" + list[1] + '月';
}

// 默认图片
export const defultImg =  function(imgUrl, type) {
  var urlImg = imgUrl;
  const imgZz = /\.(png|jpe?g|gif|svg)(\?.*)?$/;
  if (!imgZz.test(imgUrl)) {
    type === 'mbi' && (urlImg = initData.mbiDefaultImg)
    type === 'mci' && (urlImg = initData.mciDefaultImg)
    type === 'mvi' && (urlImg = initData.mviDefaultImg)
  }
  return urlImg;
}
// 细分类型
export const subType = function(arr, name) {
  
    var array = arr.concat([]);
    for (var i = 0; i < array.length; i++) {
      for (var j = i + 1; j < array.length; j++) {
        if (array[i][name] == array[j][name]) {         //第一个等同于第二个，splice方法删除第二个
          array.splice(j, 1);
          j--;
        }
      }
    }
    var newArr = [];
    for (var a = 0; a < array.length; a++ ) {
      var tem = [];
      for (var b = 0; b< arr.length; b++ ) {
        arr[b][name] === array[a][name] && tem.push(arr[b])
      }
      newArr.push({
        divideName: array[a][name],
        baseDivideId: array[a]['baseDivideId'],
        list: tem
      })
    }
    arr = newArr
    return arr;
}

export const getMbiType = function(mbiTypeNum) {
  let a = 0;
  switch (Number(mbiTypeNum)) {
      case 1101:
          a = 1
          break;
      case 1103:
          a = 2
          break;
      case 1104:
          a = 3
          break;
      case 1105:
          a = 4
          break;
  }
  return a;
}
export const getNull = (data) => {
  if (data === '' ) {
    return true
  } 
  if (data === null) {
    return true
  }
  if (data === undefined) {
    return true
  }
  if ((typeof data === 'string') &&  data.indexOf("null") >= 0) {
    return true
  }
  if ((typeof data === 'string') &&  data.indexOf("undefined") >= 0) {
    return true
  }
  return false
}
/**
 * 单位转换 w
 * @param {string} num - 数量
 * @returns {string} xxxw 转换后的值
 */
export const getChangeNum = function(num) {
  if (!getNull(num)) {
    let data = Number(num);
    if (data >= 10000) {
     return `${(data/10000).toFixed(1)}w`
    } else {
      return num
    } 
  }
  return num
}
/**
 * 
 * @param {function} fn 
 * @param {number} delay 
 * @returns 
 */
export const throttle = (fn,delay) => {
    let valid = true
    return function() {
       if(!valid){
           //休息时间 暂不接客
           return false 
       }
       // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false
        setTimeout(() => {
            fn()
            valid = true;
        }, delay)
    }
}
export const scrollTop = (number, time) => {
    if (!time) {
        document.body.scrollTop = document.documentElement.scrollTop = number
        return number
    }
    var spacingTime = 40 // 设置循环的间隔时间  值越小消耗性能越高
    var spacingInex = time / spacingTime // 计算循环的次数
    var nowTop = document.body.scrollTop + document.documentElement.scrollTop // 获取当前滚动条位置
    var everTop = (number - nowTop) / spacingInex // 计算每次滑动的距离
    var scrollTimer = setInterval(function() {
        if (spacingInex > 0) {
            spacingInex--
            scrollTop(nowTop += everTop, '')
        } else {
            clearInterval(scrollTimer) // 清除计时器
        }
    }, spacingTime)
}
//数组转化为树
export const transformTozTreeFormat = (setting, list) => {
  var i,l,
  key = setting.idKey,
  parentKey = setting.pIdKey,
  childKey = setting.children;
  let sNodes = cloneDeep(list);
  if (!key || key=="" || !sNodes) return [];
  if ("[object Array]" === Object.prototype.toString.apply(sNodes)) {
      var r = [];
      var tmpMap = [];
      for (i=0, l=sNodes.length; i<l; i++) {
          tmpMap[sNodes[i][key]] = sNodes[i];
      }
      for (i=0, l=sNodes.length; i<l; i++) {
          if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
              if (!tmpMap[sNodes[i][parentKey]][childKey])
                  tmpMap[sNodes[i][parentKey]][childKey] = [];
              tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
          } else {
              r.push(sNodes[i]);
          }
      }
      return r;
  }else {
      return [sNodes];
  }
}
// mbi pathName  
export const getMbiPathName = (typeId) => {
  return Number(typeId) === 359 ? `/tourismlist` : `/brandrankings`;
}

